<template>
  <el-card shadow="never">
    <template #header>
      <el-form label-width="80px">
        <el-row :gutter="24">
          <el-col :span="6" :xs="24">
            <el-form-item label="用户姓名">
              <el-input v-model="page.name"/>
            </el-form-item>
          </el-col>
          <el-col :span="6" :xs="24">
            <el-form-item label="手机号码">
              <el-input v-model="page.phone"/>
            </el-form-item>
          </el-col>
          <el-col :span="6" :xs="24">
            <el-form-item label="渠道商">
              <el-select v-model="page.channelId" style="width: 100%" clearable>
                <el-option v-for="item in channelList" :key="item.id" :value="item.id" :label="item.channelName"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10" :xs="24">
            <el-form-item label="导入时间">
              <el-date-picker
                  style="width: 100%"
                  v-model="page.createTimeValue"
                  type="daterange"
                  range-separator="~"
                  value-format="x"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6" :xs="24">
            <el-form-item label-width="20px">
              <el-button type="primary" @click="getTableData">查询</el-button>
              <el-button @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-col>

        </el-row>
      </el-form>
    </template>
    <div style="margin-bottom: 10px;text-align: right">
      <el-button type="primary" @click="duplicateVisible = true">去重</el-button>
    </div>
    <Table :tableData="tableData" :tableColumn="tableColumn" :page="page"
           @handleCurrentChange="(val)=>{page.pageNum = val,getTableData()}"
           @handleSizeChange="(val)=>{page.pageSize = val,getTableData()}"
    >
    </Table>
    <Dialog title="去重" v-model="duplicateVisible" @close="duplicateClear" width="40%"
            @cancel=" duplicateVisible = false"
            @confirm="duplicateConfirm"
            :confirmLoading="confirmLoading">
      <el-form ref="duplicateFormRef" :model="duplicateForm" :rules="duplicateRulesForm">
        <el-form-item label="去重范围" prop="type">
          <el-select v-model="duplicateForm.type">
            <el-option :value="1" label="指定渠道去重"></el-option>
            <el-option :value="2" label="全库去重"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="渠道名称" prop="channelId" v-if="duplicateForm.type === 1">
          <el-select v-model="duplicateForm.channelId" clearable>
            <el-option v-for="item in channelList" :key="item.id" :value="item.id" :label="item.channelName"/>
          </el-select>
        </el-form-item>
        <el-form-item label="导入名单" prop="file">
          <el-upload
              ref="uploadFileRef"
              :http-request="uploadFile"
              :limit="1"
              action="#"
              :on-remove="onRemove"
              :before-upload="beforeUpload"
              accept=".csv, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
          >
            <el-button type="primary">选择文件</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
    </Dialog>
  </el-card>
</template>

<script>
import {defineComponent, onMounted, reactive, ref, toRefs,} from 'vue'
import {fetchChannelList, channelDuplication, selectChannel} from '@/api/channel'
import {dateFormatTimeStamp} from "@/utils";
import {ElMessage, ElMessageBox} from "element-plus";
import {export_json_to_excel} from "@/utils/exportExcel";

const tableColumn = [
  {label: '姓名', prop: 'name', align: 'center'},
  {label: '手机号码', prop: 'phone', align: 'center'},
  {label: '身份证', prop: 'idCard', align: 'center'},
  {label: '渠道商', prop: 'channelName', align: 'center'},
  {label: '导入时间', prop: 'creationTime', align: 'center'},
  {label: '操作人', prop: 'systemUserName', align: 'center'},
]
export default {
  name: "Channel",
  setup() {
    const duplicateFormRef = ref(null)
    const uploadFileRef = ref(null)
    const state = reactive({
      page: {
        pageSize: 10,
        pageNum: 1,
        total: 0
      },
      channelList: [],
      tableData: [],
      duplicateVisible: false,
      duplicateForm: {
        type: null,
        file: null,
        channelId: null
      },
      duplicateRulesForm: {
        type: {
          required: true, message: '请选择文件', trigger: 'change',
        },
        channelId: {
          required: true, message: '请选择渠道', trigger: 'change',
        },
        file: {
          required: true, message: '请选择文件', trigger: 'change',
        }
      },
      confirmLoading: false
    })
    const methods = {
      async getTableData() {
        const [datetimeStart, datetimeEnd] = dateFormatTimeStamp(state.page.createTimeValue)
        const params = {
          datetimeStart, datetimeEnd,
          ...state.page,
          createTimeValue: null
        }
        const res = await fetchChannelList(params)
        if (res.code === 200) {
          const {list, total} = res.data

          state.tableData = list
          state.page.total = total
        }
      },
      beforeUpload(file) {
        state.duplicateForm.file = file
      },
      onRemove() {
        state.duplicateForm.file = null
      },
      uploadFile() {
      },
      resetSearch() {
        state.page = {
          pageSize: 10,
          pageNum: 1,
          total: 0
        }
        methods.getTableData()
      },
      duplicateClear() {
        uploadFileRef.value.clearFiles()
        duplicateFormRef.value.resetFields()
      },
      duplicateConfirm() {
        duplicateFormRef.value.validate(async v => {
          if (v) {
            const formData = new FormData()
            const {file, type, channelId} = state.duplicateForm
            formData.append('file', file)
            if (type === 1) {
              formData.append('channelId', channelId)
            }
            state.confirmLoading = true
            const res = await channelDuplication(formData)
            if (res.code === 200) {
              ElMessage.success('操作成功')
              methods.exportExcel(res.data)
              methods.getTableData()
              state.duplicateVisible = false
            }
            state.confirmLoading = false
          }
        })
      },
      exportExcel(data) {
        const list = data.map((v) => ['phone', 'name', 'idCard'].map((j) => v[j]))
        export_json_to_excel({
          header: ['电话（必填）', '姓名', '身份证'],
          data: list,
          filename: 'Data_user_template'
        })
      },
      getSelect() {
        selectChannel().then(res => {
          state.channelList = res.data
        })
      }
    }
    onMounted(() => {
      methods.getTableData()
      methods.getSelect()
    })
    return {
      uploadFileRef,
      duplicateFormRef,
      tableColumn,
      ...methods,
      ...toRefs(state)
    }
  }
}
</script>

<style scoped>

</style>
